package com.leo.config;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletRegistration;

/**
 * @ClassName: MyWebApplicationInitializer
 * @Description: 类似web.xml配置，注册bean并自启动DispatcherServlet
 * @Author: leo825
 * @Date: 2020-05-14 18:38
 * @Version: 1.0
 */
public class MyWebApplicationInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext container) {
        //创建一个Spring应用的root上下文
        AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
        applicationContext.register(ApplicationContextConfig.class);
        System.out.println("ApplicationContextConfig注册完毕");
        //监听root上下文的生命周期
        container.addListener(new ContextLoaderListener(applicationContext));
        //web上下文配置
        AnnotationConfigWebApplicationContext webApplicationContext = new AnnotationConfigWebApplicationContext();
        webApplicationContext.register(WebSpringMVCServletConfig.class);
        System.out.println("WebSpringMVCServletConfig注册完毕");
        //创建并注册DispatcherServlet
        ServletRegistration.Dynamic registration = container.addServlet("dispatcher", new DispatcherServlet(webApplicationContext));
        registration.setLoadOnStartup(1);//设置启动顺序同等：
        registration.addMapping("/");
        System.out.println("DispatcherServlet注册完毕");
    }
}
